package io.gitee.sfch.chunmi.conf;

import com.mybatisflex.annotation.KeyType;
import com.mybatisflex.core.FlexGlobalConfig;
import com.mybatisflex.core.audit.AuditManager;
import com.mybatisflex.spring.boot.MyBatisFlexCustomizer;
import io.gitee.sfch.chunmi.conf.listener.ImmutableEntityInsertListener;
import io.gitee.sfch.chunmi.conf.listener.MutableEntityInsertListener;
import io.gitee.sfch.chunmi.conf.listener.MutableEntityUpdateListener;
import io.gitee.sfch.chunmi.conf.listener.TenantImmutableEntityInsertListener;
import io.gitee.sfch.chunmi.conf.listener.TenantMutableEntityInsertListener;
import io.gitee.sfch.chunmi.entity.ImmutableEntity;
import io.gitee.sfch.chunmi.entity.MutableEntity;
import io.gitee.sfch.chunmi.entity.TenantImmutableEntity;
import io.gitee.sfch.chunmi.entity.TenantMutableEntity;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * MybatisFlex配置
 * <li> SQL审计
 * <li> ID主键选用雪花算法
 * <li> 框架数据填充
 */
@Slf4j
@Component
public class MybatisFlexConf implements MyBatisFlexCustomizer {

    @Resource
    private ImmutableEntityInsertListener immutableEntityInsertListener;
    @Resource
    private MutableEntityInsertListener mutableEntityInsertListener;
    @Resource
    private MutableEntityUpdateListener mutableEntityUpdateListener;
    @Resource
    private TenantImmutableEntityInsertListener tenantImmutableEntityInsertListener;
    @Resource
    private TenantMutableEntityInsertListener tenantMutableEntityInsertListener;

    public MybatisFlexConf() {
        //开启审计功能
        AuditManager.setAuditEnable(true);
        //设置 SQL 审计收集器
        AuditManager.setMessageCollector(auditMessage -> log.info("{}ms -> {}", auditMessage.getElapsedTime(),
                auditMessage.getFullSql().replace("`", "")));
    }

    @Override
    public void customize(FlexGlobalConfig flexGlobalConfig) {
        // 使用雪花算法生成主键
        FlexGlobalConfig.KeyConfig keyConfig = new FlexGlobalConfig.KeyConfig();
        keyConfig.setKeyType(KeyType.Generator);
        keyConfig.setValue("snowFlakeId");
        keyConfig.setBefore(true);
        flexGlobalConfig.setKeyConfig(keyConfig);
        // 新增、更新，审计和租户字段填充
        flexGlobalConfig.registerInsertListener(immutableEntityInsertListener, ImmutableEntity.class);
        flexGlobalConfig.registerInsertListener(mutableEntityInsertListener, MutableEntity.class);
        flexGlobalConfig.registerUpdateListener(mutableEntityUpdateListener, MutableEntity.class);
        flexGlobalConfig.registerInsertListener(tenantImmutableEntityInsertListener, TenantImmutableEntity.class);
        flexGlobalConfig.registerInsertListener(tenantMutableEntityInsertListener, TenantMutableEntity.class);
    }
}
